<?php

declare(strict_types=1);

namespace App\Job;

use App\Event\UserOnlineEvent;
use App\Helpers\Helper;
use App\Helpers\RedisUtil;
use App\Model\UserActLog;
use App\Model\User;
use App\Model\UserProfile;
use Hyperf\AsyncQueue\Job;
use Psr\EventDispatcher\EventDispatcherInterface;

class ProcessOnlineStatusCallback extends Job
{
    public $callbackInfo;

    public function __construct($callbackInfo = [])
    {
        $this->callbackInfo = $callbackInfo;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        foreach ($this->callbackInfo as $k => $callbackInfo) {
            if (!in_array($k, ['0', '1', '2'])) continue;
            // log_info(__CLASS__ . "==online==" . json_encode($callbackInfo));
            $this->doProcess($callbackInfo);
        }
        return;
    }

    /**
     * 处理单个用户回调
     * @param array $callbackInfo
     */
    protected function doProcess($callbackInfo = [])
    {
        $imAccount = $callbackInfo['userid'];
        $online = $callbackInfo['status'] == '0' ? 1 : 0;
        $userIds = User::getUserIdByIm($imAccount, 'id');
        if (!$userIds) return;

        //更新在线状态
        UserProfile::whereIn('user_id', $userIds)->update([
            'online' => $online,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        log_info(__CLASS__ . "==ImAccount:{$imAccount}==Online:{$online}==" . json_encode($userIds));

        //添加行为日志
        UserActLog::addRecord($userIds[0], $online ? UserActLog::ACT_ONLINE : UserActLog::ACT_OFFLINE);

        if ($online == 1) {
            //触发用户上线事件
            make(EventDispatcherInterface::class)->dispatch(new UserOnlineEvent($userIds, $online));
        }
        return;
    }
}
